package com.lihui.stack;

import java.util.Arrays;

/**
 * 功能描述
 *
 * @author wileda
 * @date 2022/10/18  15:39
 */

public class MyStack {
    private int[] elementData;
    private int size;
    private final int DEFAULT_CAPACITY = 5;

    public MyStack(int capacity) {
        if (capacity < 0) {
            throw new RuntimeException("数组容量不能小于0");
        } else if (capacity > 0) {
            this.elementData = new int[capacity];
        }else {
            this.elementData = new int[DEFAULT_CAPACITY];
        }
    }

    public void push(int data){
        ensureCapacity();
        elementData[size] = data;
        size++;
    }
    private void ensureCapacity() {
        if (size == elementData.length) {
            this.elementData = Arrays.copyOf(elementData, elementData.length * 2);
        }
    }

    public int pop(){
        int top = peek();
        size--;
        return top;
    }
    public int peek(){
        if (size < 0){
            throw new RuntimeException("栈为空");
        }
        int top = elementData[size - 1];
        return top;

    }
}
